package com.asambleacristiana.reportes;

import java.io.File;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.j2ee.servlets.BaseHttpServlet;

import com.asambleacristiana.repository.dao.JdbcDataSource;
import com.asambleacristiana.utils.Commons;

public abstract class AbstractBaseReportBean extends Commons {

	public enum ExportOption {
		PDF, HTML, EXCEL, RTF
	}

	private ExportOption exportOption;

	private final String COMPILE_DIR = "/reportes/";

	public AbstractBaseReportBean() {
		super();
		setExportOption(ExportOption.PDF);
	}

	protected void prepareReport() throws Exception {
		Connection conn = null;
		try {
			conn = JdbcDataSource.getInstance().getDataSource().getConnection();
			ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

			ServletContext context = (ServletContext) externalContext.getContext();
			HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
			HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

			ReportConfigUtil.compileReport(context, getCompileDir(), getCompileFileName());

			File reportFile = new File(ReportConfigUtil.getJasperFilePath(context, getCompileDir(), getCompileFileName() + ".jasper"));

			JasperPrint jasperPrint = ReportConfigUtil.fillReport(reportFile, getReportParameters(), conn);

			if (getExportOption().equals(ExportOption.HTML)) {
				ReportConfigUtil.exportReportAsHtml(jasperPrint, response.getWriter());
			} else {
				request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
				response.sendRedirect(request.getContextPath() + "/servlets/report/" + getExportOption());
			}
			FacesContext.getCurrentInstance().responseComplete();
		} catch (Exception e) {
			throw e;
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
	}

	public ExportOption getExportOption() {
		return exportOption;
	}

	public void setExportOption(ExportOption exportOption) {
		this.exportOption = exportOption;
	}

	protected Map<String, Object> getReportParameters() {
		Map<String,Object> parameters = new HashMap<String, Object>();
		Locale locale = new Locale("es","AR");
		parameters.put(JRParameter.REPORT_LOCALE, locale);
		return parameters;
	}

	protected String getCompileDir() {
		return COMPILE_DIR;
	}

	protected abstract JRDataSource getJRDataSource();

	protected abstract String getCompileFileName();
}